<template>
    <div>
        <div v-show="$route.path !== '/audit'">
          <router-view></router-view>
        </div>
        <div v-show="$route.path === '/audit'">
        <el-button type="primary" :icon="Link" style="margin-right: 20px;" @click="addDialog = true" v-if="$store.state.user.role !== 'ROLE_ADMIN'">反馈</el-button>
        <el-select v-model="dispose" placeholder="处理状态" style="margin-right: 20px;" @change="selectStatus">
          <el-option label="已处理" value="1"/>
          <el-option label="未处理" value="0"/>
        </el-select>
        <el-button type="success" @click="getAll">全部反馈</el-button>
        <el-dialog :append-to-body="true" draggable v-model="addDialog" title="反馈" width="60%">
            <el-form :model="addData" label-width="70px">
              <el-form-item  label="关键字">
                <el-input v-model="addData.keyword" style="width: 40%;" maxlength="8" show-word-limit />
              </el-form-item>
              <el-form-item label="内容">
                <div style="border: 2px solid #ccc ;" >
                    <Toolbar
                        style="border-bottom: 1px solid #ccc"
                        :editor="editorRef"
                        :defaultConfig="toolbarConfig"
                        mode="simple"
                    />
                    <Editor
                        style="height: 320px; overflow-y: hidden;"
                        v-model="addData.content"
                        :defaultConfig="editorConfig"
                        mode="simple"
                        @onCreated="handleCreated"
                    />
                </div>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="addDialog = false">关闭</el-button>
                <el-button type="primary" @click="addFeedBack">
                  添加
                </el-button>
              </span>
            </template>
          </el-dialog>
        <el-row>
            <el-col
                v-for="(feedback,index) in feedbacks"
                :key="feedback.id"
                :span="5"
                :offset="index % 4 === 0 ? 0 : 1"
            >
            <el-card :body-style="{ padding: '0px' }" style="margin-top: 20px;">
                <el-row style="padding: 8px">
                  <el-col :span="7">
                    <img :src="feedback.avatar" class="image"/>
                  </el-col>
                  <el-col :span="17">
                    <el-button text type="info" style="margin-bottom: 5px;float: right;">{{feedback.submitTime}}</el-button>
                    <el-button :disabled="true"  type="info" style="float: right;">{{feedback.keyword}}</el-button>
                  </el-col>
                </el-row>
                <el-divider />
              <div style="padding: 8px">
                <el-tag  v-if="feedback.status === true"  type="success" >已处理</el-tag>
                <el-tag  v-if="feedback.status === false" type="warning" >未处理</el-tag>
                <time v-if="feedback.processTime !== null" class="time" style="float: right;">
                    <el-icon><Timer /></el-icon>
                    {{feedback.processTime}} 
                </time>
                <time v-else class="time" style="float: right;">
                    <span v-if="$store.state.user.role !== 'ROLE_ADMIN'">等待处理！</span>
                    <span v-else>请尽快处理！</span>
                </time>
                <div class="bottom">
                  <el-button type="primary" :icon="Promotion" @click="ViewContent(feedback.id)">查看</el-button>
                  <el-popconfirm
                        width="220"
                        confirm-button-text="确认"
                        cancel-button-text="我再想想"
                        cancel-button-type="info"
                        :icon="InfoFilled"
                        icon-color="red"
                        title="你确定删除吗?"
                        @confirm="deleteFeedBack(feedback.id)"
                  >
                        <template #reference>
                          <el-button type="danger" :icon="Delete">删除</el-button>
                        </template>
                 </el-popconfirm>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        </div>
    </div>
</template>
<script>
    import request from '@/utils/request';
    import {useRouter,useRoute} from 'vue-router'
    import '@wangeditor/editor/dist/css/style.css' // 引入 css
    import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
    import {onBeforeUnmount, ref, shallowRef,watch} from 'vue';
    import {useStore} from 'vuex';
    import {ElMessage} from 'element-plus';
    import {Delete,Promotion,Link,InfoFilled} from '@element-plus/icons-vue'
    export default{
        name:'AuditMessage',
        components:{
            Editor, 
            Toolbar
        },
        setup() {
            const store = useStore();
            const router = useRouter();
            const route = useRoute();
            const icon = {Delete,Promotion,Link,InfoFilled};
            let addDialog = ref(false)
            let feedbacks = ref([])
            let dispose = ref('')
            // 编辑器实例
            const editorRef = shallowRef()


            let addData = ref({
                username:store.state.user.username,
                avatar:store.state.user.photo,
                keyword:'',
                content:'',
            })

            let selectStatus = () => {
              let status = false
              if(dispose.value === '1')
                status = true;
              request({
                  url:'/feedback/getByStatus/',
                  method:'get',
                  params:{
                    role:store.state.user.role,
                    username:store.state.user.username,
                    status:status, 
                  },
                  headers:{
                    Authorization:"Bearer "+store.state.user.token,
                  },
              }).then((resp) => {
                feedbacks.value = resp
              }).catch(() => {});
            }
            const toolbarConfig = {}
            const editorConfig = { 
              placeholder: '请输入内容...',
              MENU_CONF:{
                  // 配置上传图片
                  uploadImage:{
                      // 请求路径
                      server: "http://localhost:3030/user/upload/avatar/",
                      // 后端接收的文件名称
                      fieldName: "file",
                      maxFileSize: 10 * 1024 * 1024, // 1M
                      // 上传的图片类型
                      allowedFileTypes: ["image/*"],
                      // 小于该值就插入 base64 格式（而不上传），默认为 0
                      base64LimitSize: 10 * 1024, // 10MB
                      customInsert(resp,insertFn) {
                        console.log(resp,"@")
                        insertFn("http://localhost:3030" + resp.avatarUrl)
                      },
                      headers:{
                        Authorization:"Bearer "+store.state.user.token,
                      },
                      // 单个文件上传成功之后
                      onSuccess(resp) {
                        console.log(resp)
                      },
                  }
              }
            }

            // 组件销毁时，也及时销毁编辑器
            onBeforeUnmount(() => {
                const editor = editorRef.value
                if (editor == null) return
                editor.destroy()
            })

            const handleCreated = (editor) => {
                editorRef.value = editor 
            }
            let getAll = () => {
                request({
                    url:'/feedback/all/',
                    method:'get',
                    params:{
                        role:store.state.user.role,
                        username:store.state.user.username
                    },
                    headers:{
                      Authorization:"Bearer "+store.state.user.token,
                    },
                }).then((resp) => {
                    feedbacks.value = resp;
                }).catch(() => {});
            }
            getAll();
            let  addFeedBack = () => {
                addDialog.value = false;
                request({
                    url:'/feedback/add/',
                    method:'post',
                    data:{
                      ...addData.value
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    },
                }).then((resp) => {
                  if(resp.message === 'success'){
                    getAll()
                    ElMessage({ message:"添加成功！", grouping: true,type: 'success',})
                  }
                }).catch(() => {});
            }
            let ViewContent = (id) => {
              router.push({
                path:'/audit/' + id,
              })
            }
            watch(() => route.path,() => {getAll()},{ immediate: true });
            let deleteFeedBack = (id) => {
                request({
                    url:'/feedback/delete/',
                    method:'post',
                    data:{
                      id,
                    },
                    headers:{
                      Authorization:"Bearer "+store.state.user.token,
                    },
                }).then((resp) => {
                  if(resp.message === 'success'){
                    getAll()
                    ElMessage({ message:"删除成功！", grouping: true,type: 'success',})
                  }
                }).catch(() => {});
            }
            return {
                feedbacks,
                addFeedBack,
                ...icon,
                addData,
                editorRef,
                toolbarConfig,
                editorConfig,
                handleCreated,
                getAll,
                addDialog,
                deleteFeedBack,
                ViewContent,
                dispose,
                selectStatus,
            }
        },
    }
</script>
<style scoped> 
.time {
  font-size: 14px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.image {
  width: 100%;
  display: block;
  border-radius: 25%;
  border: 2px solid rgb(73, 5, 5);
}
</style>